package com.yanqu.road.server.cmd.marriage;

import com.yanqu.road.entity.marriage.MarriageInfo;
import com.yanqu.road.entity.servercenter.group.CrossMarriageGroup;
import com.yanqu.road.logic.pb.MarriagePb;
import com.yanqu.road.pb.marriage.CrossMarriageProto;
import com.yanqu.road.pb.marriage.MarriageProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.marriage.CrossGroupMarriageMgr;
import com.yanqu.road.server.manger.CrossMarriageGroupMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;

import java.util.List;

@Cmd(code = Protocol.C_REFUSE_MARRIAGE, desc = "拒绝跨服联姻")
public class CrossMarriageRefuseCmd extends CrossCommand {
    private long userId;
    private String childUid;
    private CrossMarriageGroup marriageGroup;
    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        CrossMarriageProto.CrossMarriageApplyRefuseReqMsg reqMsg = CrossMarriageProto.CrossMarriageApplyRefuseReqMsg.parseFrom(packet.getBytes());
        childUid = reqMsg.getChildUid();
        userId = packet.getPlayerId();
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        marriageGroup = CrossMarriageGroupMgr.getCrossMarriageGroupByServerId(serverId);
        if(!CrossMarriageGroupMgr.canCrossMarriage(marriageGroup)){
            ret = GameErrorCode.E_CROSS_MARRIAGE_NO_OPEN;
            return;
        }
        if(StringUtils.isNullOrEmpty(childUid)){
            ret = CrossGroupMarriageMgr.refuseAllMarriage(marriageGroup.getGroupId(), serverId, userId);
        }else {
            ret = CrossGroupMarriageMgr.refuseMarriage(marriageGroup.getGroupId(), serverId, userId, childUid);
        }
    }

    @Override
    public void sendData() {
        CrossMarriageProto.CrossMarriageApplyRefuseRespMsg.Builder respMsg = CrossMarriageProto.CrossMarriageApplyRefuseRespMsg.newBuilder();
        respMsg.setRet(ret);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_CROSS_MARRIAGE_APPLY_REFUSE, respMsg);
        MessageHelper.sendPacket(serverId, userId, pbMsg);
        if(StringUtils.isNullOrEmpty(childUid) && 0 == ret){
            List<MarriageInfo> marriageInfoList = CrossGroupMarriageMgr.getAppointApply(marriageGroup.getGroupId(), serverId, userId);
            MarriageProto.MarriageApplyListMsg.Builder listMsg = MarriagePb.parseMarriageApplyListMsg(marriageInfoList);
            YanQuMessage pbListMsg = YanQuMessageUtils.buildMessage(Protocol.U_CROSS_MARRIAGE_APPOINT_APPLY_LIST, listMsg);
            MessageHelper.sendPacket(serverId, userId, pbListMsg);
        }
    }
}
